package com.brp2p.controller.mobile;

import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.brp2p.persistence.entity.AccountBankCard;
import com.brp2p.persistence.entity.AccountCapital;
import com.brp2p.persistence.entity.User;
import com.brp2p.persistence.mapper.UserMapper;
import com.brp2p.service.AccountCapitalService;
import com.brp2p.service.BaseControllerInterface;
import com.brp2p.service.UserService;
import com.brp2p.service.enums.Account.Type;
import com.brp2p.service.promotion.PromotionVoucherService;
import com.brp2p.utils.AjaxMsg;
import com.brp2p.utils.BaseSupport;
import com.brp2p.utils.EncryptUtil;
import com.brp2p.utils.MobileClientUtils;

@Controller
@RequestMapping("mobile/user")
public class MobileUserController extends BaseSupport {
	
	@Autowired
	UserService userService;
	@Autowired
    BaseControllerInterface baseControllerInterface;
	@Autowired
	AccountCapitalService accountCapitalService;
	@Autowired
	PromotionVoucherService promotionVoucherService;
	@Autowired
	private UserMapper userMapper;
	
	/**
	 * 邦融理财移动设备  我的邦融  个人中心登录接口
	 * @return
	 **/
	@RequestMapping(value="personalCenter")
	public @ResponseBody String getPersonInfo(HttpServletRequest request, HttpServletResponse response){
		AjaxMsg ajaxMsg = null;
		//判断用户是否登录
		Long user_id= MobileClientUtils.isLogin(request);
		if(user_id == null){//未登录
			ajaxMsg = AjaxMsg.newError().addMessage("尚未登录，请登录！");
		}else{//已登录
			ajaxMsg = AjaxMsg.newSuccess();
			User user = userService.getUserById(user_id);
			//设置密码不可见
			user.setUser_pwd("");
			//获得资金账户
			AccountCapital accountCapital = accountCapitalService.getAccountCapitalByUser(Type.valueOf(user.getUser_type()),user.getUser_id());
			user.setCapital(accountCapital);
			//年券总计
			Double bigDecimal = promotionVoucherService.getSum(user_id);
			//次券总计
			Double acpitalSum = promotionVoucherService.getAcapitalSum(user_id);
			//银行卡账号
			AccountBankCard bankCard = accountCapitalService.getBankCard(user_id);//为空就没有绑定银行卡
			//银行卡号处理，将银行卡号第一位到倒数五位设置为掩码*
			if(bankCard != null){
				String card_num_init = bankCard.getCard_num().trim();
				if(card_num_init.length() >= 4){
					card_num_init = "**************"+card_num_init.substring(card_num_init.length()-4, card_num_init.length());
				}
				bankCard.setCard_num(card_num_init);
			}
			//邀请好友数
			Integer recommendUsersCount = userService.getUserListByRecommend(user_id).size();
			
			// 写入会员登录Session
			request.getSession().setAttribute(User.LOGIN_USER_ID_SESSION_NAME, user.getUser_id());
			request.getSession().setAttribute(User.LOGIN_NICK_SESSION_NAME, user.getUser_nick());
			request.getSession().setAttribute("user", user);
			
			ajaxMsg.addData("user", user);//用户基本信息
			ajaxMsg.addData("bigDecimal", bigDecimal);//年券总计
			ajaxMsg.addData("acpitalSum", acpitalSum);//次券总计
			ajaxMsg.addData("bankCard", bankCard);//银行卡信息
			ajaxMsg.addData("recommendUsersCount", recommendUsersCount);//推荐人总数
		}
		return ajaxMsg.toJson();
	}
	
	/**
	 * 手机客户端   注册新用户
	 * @param user 用户基本信息
	 * session Parameters:recmderPhone 推荐人手机号码
	 * @return
	 **/
	@RequestMapping(value="newUser")
	public @ResponseBody String newRegister(HttpServletRequest request, HttpServletResponse response,User user){
		AjaxMsg ajaxMsg = null;
		/**
		 * 0.  检验服务器保存手机验证码是否到期，到期则推出
		 * 1.  检验用户的验证码输入是否和已发送的验证码一致，不一致则返回数据
		 * 2.  检验用户输入的手机号码，和发送接收验证码的手机号码是否一致，不一致则返回错误提示。
		 * 3.  检验用户是否已经存在，如果存在，则返回错误提示：该手机已经被注册
		 * problem: 是否要加入格式验证
		 * 4.  根据邀请码是否为空，验证是否有邀请人：(网页端)邀请码存在两个位置：a.URL地址recommended变量 b. 用户输入的推荐码
		 *    4.1  有邀请人，则查询邀请人信息，若存在则进行优惠券赠送，否则返回错误：邀请码不存在
		 *    4.2 没有邀请人，则进行数据的插入
		 * 5.  session相关数据保存更新
		 */
		//检查手机号码是否已经被注册
		String user_phone = user.getUser_phone();
		int count = userService.checkPhoneUnion(user_phone);
		if(count > 0){//已注册
			ajaxMsg =  AjaxMsg.newError().addMessage("该手机号已经注册！");
			return ajaxMsg.toJson();
		}else{//可以注册
			//加密用户密码
			user.setUser_pwd(EncryptUtil.getMD5EncryptString(user.getUser_pwd()));
			//设置用户初始昵称
			user.setUser_nick(user.getUser_phone().substring(0,3)+"*****"+user.getUser_phone().substring(8,11));
			//设置注册类型
			user.setUser_type(String.valueOf(com.brp2p.service.enums.User.Type.REGULAR));
			//设置用户注册时间
			user.setUser_create_time(new Date());
			//设置用户的认证码
			user.setUser_identification_code(UUID.randomUUID().toString());
			//获取用户的推荐人信息
			String recmderPhone = request.getParameter("recmderPhone");
			if(recmderPhone != null && !"".equals(recmderPhone)){
				
				//判断推荐码是否存在 
				User reCmder = userService.getUserByUphone(com.brp2p.service.enums.User.Type.REGULAR, recmderPhone);
		    	if(reCmder == null){
		    		ajaxMsg = AjaxMsg.newError().addMessage("推荐码不存在！"); 
		    		return ajaxMsg.toJson();
		    	}else{//推荐码正确
		    		user.setUser_recommended(reCmder.getUser_id());
		    		//userService.registerUser(user);
		    	}
		    }
			//保存新用户
			userService.registerUser(user);
			//需要修改，这里的user_id 可能取不到
			// 写入会员登录Session
			user.setUser_pwd("");
			ajaxMsg.addData("user", user);
			//request.setAttribute("user", user);
			request.getSession().setAttribute(User.LOGIN_USER_ID_SESSION_NAME, user.getUser_id());//用户登录session  userid   loginUserId
			request.getSession().setAttribute(User.LOGIN_NICK_SESSION_NAME, user.getUser_nick());// 用户登录昵称  session
			ajaxMsg = AjaxMsg.newSuccess().addMessage("恭喜，注册成功！");
			
			return ajaxMsg.toJson();
		}
		
	}
	
	/**
	 * 修改  账户密码
	 * @param user_pwd, user_re_pwd , user_pwd_old
	 * @return
	 */
	@RequestMapping(value="changePwd")
	public @ResponseBody String changePassword(HttpServletRequest request, HttpServletResponse response){
		// 1. 获取当前session中保存的用户，并判断用户的session是否还存在
		AjaxMsg ajaxMsg = null;
		String newPwd = request.getParameter("user_pwd");//新密码
		String rePwd  = request.getParameter("user_re_pwd");//重复密码
		String oldPwd = request.getParameter("user_pwd_old");//旧密码
		
		// 2. 获取登录session中的用户
		Long session_user_id = (Long)request.getSession(true).getAttribute(User.LOGIN_USER_ID_SESSION_NAME);
		if(null == session_user_id || session_user_id == 0){
			ajaxMsg = AjaxMsg.newError().addMessage("用户登录已超市，请您重新登录！");
			return ajaxMsg.toJson();
		}
		// 3. 查询数据库中的User
		User user = userService.getUserById(session_user_id);
		if(user == null){
			ajaxMsg = AjaxMsg.newError().addMessage("系统查询数据失败！");
			return ajaxMsg.toJson();
		}
		// 4. 判断用户的旧密码是否和数据库一致
		if(!user.getUser_pwd().equals(oldPwd)){
			ajaxMsg = AjaxMsg.newError().addMessage("旧密码输入错误！");
			return ajaxMsg.toJson();
		}
		// 5. 判断密码格式是否正确
		Pattern pt = Pattern.compile("[a-zA-Z0-9_]*");//为true表示是有着三种组成的
		Matcher mc = pt.matcher(newPwd);
		boolean bol = mc.matches();
		if(newPwd == null || "".equals(newPwd) || newPwd.length() < 6 || !bol){
			ajaxMsg = AjaxMsg.newError().addMessage("密码格式错误！");
			return ajaxMsg.toJson();
		}
		// 6. 判断两次输入的密码是否一致
		if(!(""+newPwd).equals(rePwd)){
			ajaxMsg = AjaxMsg.newError().addMessage("两次输入的密码不一致！");
			return ajaxMsg.toJson();
		}
		// 7. 检查通过，进行密码的修改
		user.setUser_pwd(newPwd);
		userService.updatePwd(user);
		
		ajaxMsg = AjaxMsg.newSuccess().addMessage("更新成功");
		return ajaxMsg.toJson();
	}
	
	/**
	 * 忘记密码，通过手机验证码重设密码
	 * @param  用户手机：user_phone , 用户新密码：user_pwd_new ,重复密码：user_re_pwd_new， 用户手机验证码：validCode
	 * @return 
	 */
	@RequestMapping(value="resetPwd")
	public @ResponseBody String resetPasswordWhenForgot(HttpServletRequest request, HttpServletResponse response){
		AjaxMsg ajaxMsg = null;
		String user_phone = request.getParameter("user_phone");
		String user_pwd_new = request.getParameter("user_pwd_new");
		String user_re_pwd_new = request.getParameter("user_re_pwd_new");
		String validCode_user = request.getParameter("validCode");
		
		String forgetPhoneCode = request.getSession().getAttribute("forgetPwdPhone").toString();
		String validCode_sys =  request.getSession().getAttribute("Forget_phoneCodeNum").toString();
		
		// 1. 获取手机验证码是否已过期
		if(validCode_sys == null || validCode_sys.equals("") || validCode_sys.equals("null")){
			ajaxMsg = AjaxMsg.newError().addMessage("短信验证码已过期！");
			return ajaxMsg.toJson();
		}
		// 2. 校验输入的验证码，是否和发送的验证码一致
		if(!validCode_sys.equals(validCode_user)){
			ajaxMsg = AjaxMsg.newError().addMessage("短信验证码错误！");
			return ajaxMsg.toJson();
		}
		// 3. 校验手机号码和接收验证码的手机号码是否一致
		if(user_phone == null || !user_phone.equals(forgetPhoneCode)){
			ajaxMsg = AjaxMsg.newError().addMessage("接收验证码手机和当前手机号不一致!");
			return ajaxMsg.toJson();
		}
		// 4. 校验密码格式
		Pattern pt = Pattern.compile("[a-zA-Z0-9_]*");//为true表示是有着三种组成的
		Matcher mc = pt.matcher(user_pwd_new);
		boolean bol = mc.matches();
		if(user_pwd_new == null || "".equals(user_pwd_new) || user_pwd_new.length() < 6 || !bol){
			ajaxMsg = AjaxMsg.newError().addMessage("密码格式错误！");
			return ajaxMsg.toJson();
		}
		if(!(user_pwd_new).equals(user_re_pwd_new)){
			ajaxMsg = AjaxMsg.newError().addMessage("两次输入密码一致！");
			return ajaxMsg.toJson();
		}
		// 5. 进行密码修改
		User  user = new User();
		if(user_phone.contains("@")){
			 user = userService.getUserByEmail(com.brp2p.service.enums.User.Type.REGULAR, user_phone);
		}else{
			 user = userService.getUserByUphone(com.brp2p.service.enums.User.Type.REGULAR, user_phone);
		}
		user.setUser_pwd(EncryptUtil.getMD5EncryptString(user_pwd_new));
		userService.updatePwd(user);
		ajaxMsg = AjaxMsg.newSuccess().addMessage("密码重置成功！");
//		user.setUser_pwd("");
//		ajaxMsg.addData("user", user);
		
		return ajaxMsg.toJson();
	}
	
	/**
	 * 
	 * @param login_account 账号   login_pwd 密码
	 * @return
	 */
	@RequestMapping(value="mobileLogin")
	public @ResponseBody String mobileLogin(HttpServletRequest request, HttpServletResponse response){
		 AjaxMsg ajaxMsg = null;
		 //1. 获取用户传递的用户账号和密码 参数
		 String account = request.getParameter("login_account");
		 String pwd		= request.getParameter("login_pwd");
		 //2. 校验用户名密码，预防空指针
		 if(account == null || account.equals("") || pwd == null || pwd.equals("")){
			 ajaxMsg = AjaxMsg.newError().addMessage("账号、密码不能为空！");
			 return ajaxMsg.toJson();
		 }
		 //3. 校验用户
		 if(account.contains("@")){
			 ajaxMsg = userService.verifyUser(com.brp2p.service.enums.User.Type.REGULAR, account, pwd);
		 }else{
			 ajaxMsg = userService.verifyUserByPhoneNum(com.brp2p.service.enums.User.Type.REGULAR, account, pwd);
		 }
		 //4. 判断校验是否成功
		 if(!ajaxMsg.isSuccess()){
			 return ajaxMsg.toJson();
		 }
		//5. 登录成功，记录最后登录时间
		 User user = (User)ajaxMsg.getData("user");
		 user.setLast_login_time(new Date());
		 user.setUser_pwd("");
		 userMapper.updateUser(user);
		//6. 写入会员登录Session
		request.getSession().setAttribute(User.LOGIN_USER_ID_SESSION_NAME, user.getUser_id());
		request.getSession().setAttribute(User.LOGIN_NICK_SESSION_NAME, user.getUser_nick());
		//request.getSession().setAttribute("User", user);
		//7. 返回程序数据 user 对象
		ajaxMsg = AjaxMsg.newSuccess().addData("user", user);
		return ajaxMsg.toJson();
	}
	
	
	
	
	
	
	
	
	
	
	
	
}
